//
//  frame_factroy.c
//  knx_lib
//
//  Created by zym on 13-5-24.
//  Copyright (c) 2013年 Hinwo. All rights reserved.
//

#include "frame_interface.h"
#include "qt_knx.h"

void frame_set_header(_u8 msg[],_u16 *msg_len)
{
    msg[0] = 0x06;      // Header size: 6 bytes
    msg[1] = 0x10;      // EIBnet IP Version
    
    *msg_len += 2;
}
 
void frame_set_cmd(_u8 msg[],_u16 cmd,_u16 *msg_len)
{
    msg[0] = U16_BYTE_HI(cmd);      //  (2 bytes)
    msg[1] = U16_BYTE_LOW(cmd);      //  -- '' --
    
    if(msg_len!=NULL)
        *msg_len += 2; 
}

void frame_padding_total_size(_u8 msg[],_u16 *msg_len)
{
    msg[0] = 0xff;      //  (2 bytes)
    msg[1] = 0xff;      //  -- '' --
    
    *msg_len += 2;
}

void frame_set_tunnelling_struct(_u8 msg[],_u8 cid,_u8 sc,_u16 *msg_len)
{
    msg[0] = 0x04;     //  (2 bytes)
    msg[1] = cid;      //
    msg[2] = sc;       //
    msg[3] = 0x00;     // reserved or errorcode
    
    *msg_len += 4;
}

_u16 frame_get_cmd(_u8* msg)
{
    return (_u16)((msg[2]<<8)|msg[3]);
}

void fram_set_total_len(_u8 msg[],_u16 total)
{
    if(total>256)
    {
        qDebug("error total size: %u \n",total);
        return;
    }
    
    msg[4] = U16_BYTE_HI(total);      // size (2 bytes)
    msg[5] = U16_BYTE_LOW(total);      //  -- '' --
}

void package_cmei_msg(_u8 msg[],_u8 msg_code,_u8 addtion,_u8 controlField1,_u8 controlField2,_u8 addr[2],_u16 *msg_len)
{
    // cEMI frame ----------------------------------------------
    
//    int controlField1 = 0xba;      //not repeat, low
//    int controlField2 = 0xd0;      //group address
    
    msg[0] = msg_code;     // message code
    msg[1] = addtion;     // additional info length : 0
    msg[2] = controlField1;
    msg[3] = controlField2;
    msg[4] = 0x00;     // source address hi byte  (to be filled by gateway)
    msg[5] = 0x00;     // source address lo byte  (to be filled by gateway)
    
    msg[6] = addr[0];     // dest address hi byte
    msg[7] = addr[1];     // dest address lo byte
    
    *msg_len += 8;
}

void package_cmei_msg_data(_u8 msg[],_u8 tpci_apci,_u8 data[],_u8 data_len,_u16 *msg_len)
{
    msg[0] = data_len;     // data len
    msg[1] = tpci_apci;     // TPCI/APCI
    
    strncpy((char *)&msg[2],(char *)data,data_len);
    
    // 2 means data_len & tpci_apci
    *msg_len += 2+data_len;
         
}
